import urllib.request as ur
import lxml.etree as le
import user_agent

keyword = input('请输入关键词：')
pn_start = int(input('起始页：'))
pn_end = int(input('终止页：'))

# 定义请求方法
def getRequest(url):
    return ur.Request(
        url=url,
        headers={
            # 请求头伪装
            'User-Agent':user_agent.get_user_agent_pc(),
        }
    )

# 定义代理IP地址方法
def getProxyOpener():
    proxy_address = ur.urlopen('http://api.ip.data5u.com/dynamic/get.html?order=d07fe1b9415a935eebe32ec7af913b44&sep=3').read().decode('utf-8').strip()
    proxy_handler = ur.ProxyHandler(
        {
            'http':proxy_address
        }
    )
    return ur.build_opener(proxy_handler)

# 对请求进行循环
for pn in range(pn_start,pn_end+1):
    request = getRequest(
        'https://so.csdn.net/so/search/s.do?p=%s&q=%s&t=blog&viparticle=&domain=&o=&s=&u=&l=&f=&rbg=0' % (pn,keyword)
    )
    # 请求可能出现异常
    try:
        response = getProxyOpener().open(request).read()
        # 通过Xpath语句测试获得
        href_s = le.HTML(response).xpath('//span[@class="down fr"]/../span[@class="link"]/a/@href')
        for href in href_s:
            # 请求可能出现异常
            try:
                response_blog = getProxyOpener().open(
                    getRequest(href)
                ).read()
                # 通过Xpath语句测试获得
                title = le.HTML(response_blog).xpath('//h1[@class="title-article"]/text()')[0]
                print(title)
                with open('blog/%s.html' % title,'wb') as f:
                    f.write(response_blog)
            except Exception as e:
                print(e)
    except:
        pass